import 'package:flutter/material.dart';
import '../../utils/theme_colors.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import '../../app_routes.dart';

class HRCNonHeritageDigitizationScreen extends StatefulWidget {
  const HRCNonHeritageDigitizationScreen({super.key});

  @override
  _HRCNonHeritageDigitizationScreenState createState() => _HRCNonHeritageDigitizationScreenState();
}

class _HRCNonHeritageDigitizationScreenState extends State<HRCNonHeritageDigitizationScreen> {
  File? _selectedImage;
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _descriptionController = TextEditingController();
  final TextEditingController _categoryController = TextEditingController();
  final TextEditingController _artistController = TextEditingController();
  String _selectedHeritageType = '传统工艺';
  bool _isSubmitting = false;

  // 非遗类型列表
  final List<String> _heritageTypes = [
    '传统工艺',
    '传统音乐',
    '传统舞蹈',
    '传统戏剧',
    '传统美术',
    '传统医药',
    '传统体育',
    '民俗活动',
  ];

  // 选择图片
  Future<void> _pickImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      setState(() {
        _selectedImage = File(image.path);
      });
    }
  }

  // 构建步骤指示器
  Widget _buildStepIndicator(String label, bool isActive) {
    return Column(
      children: [
        Container(
          width: 36,
          height: 36,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: isActive ? ThemeColors.primary : ThemeColors.background,
            border: Border.all(
              color: isActive ? ThemeColors.primary : ThemeColors.border,
              width: 1,
            ),
          ),
          child: Center(
            child: Text(
              '${_getStepNumber(label)}',
              style: TextStyle(
                color: isActive ? Colors.white : ThemeColors.textSecondary,
                fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
                fontSize: 16,
              ),
            ),
          ),
        ),
        const SizedBox(height: 8),
        SizedBox(
          width: 60,
          child: Text(
            label,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12,
              color: isActive ? ThemeColors.primary : ThemeColors.textSecondary,
              fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      ],
    );
  }

  // 构建步骤连接器
  Widget _buildStepConnector(bool isActive) {
    return Expanded(
      child: Container(
        height: 2,
        margin: const EdgeInsets.symmetric(horizontal: 4),
        color: isActive ? ThemeColors.primary : ThemeColors.border,
      ),
    );
  }

  // 获取步骤编号
  String _getStepNumber(String label) {
    switch (label) {
      case '资产上传':
        return '1';
      case '认证评估':
        return '2';
      case '价值锚定':
        return '3';
      case '生成通证':
        return '4';
      case '上链完成':
        return '5';
      default:
        return '0';
    }
  }

  // 提交数字化请求
  Future<void> _submitDigitization() async {
    setState(() {
      _isSubmitting = true;
    });

    try {
      // 模拟API请求延迟
      await Future.delayed(const Duration(seconds: 2));
      // 这里可以添加实际的上链API调用
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('资产已成功提交，正在跳转到认证评估页面')),
      );
      
      // 延迟后跳转到认证评估页面
      await Future.delayed(const Duration(seconds: 1));
      Navigator.pushNamed(context, AppRoutes.authenticationEvaluation);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('上链失败：$e')),
      );
    } finally {
      setState(() {
        _isSubmitting = false;
      });
    }
  }

  // 显示成功对话框
  void _showSuccessDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          elevation: 4,
          child: Container(
            padding: const EdgeInsets.all(24.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children:
                [
                  Container(
                    width: 80,
                    height: 80,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: ThemeColors.success.withOpacity(0.1),
                    ),
                    child: const Icon(
                      Icons.check,
                      size: 48,
                      color: ThemeColors.success,
                    ),
                  ),
                  const SizedBox(height: 20),
                  const Text(
                    '上链成功',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                      color: ThemeColors.textPrimary,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    '您的非遗资产已成功上链，资产ID：#${DateTime.now().millisecondsSinceEpoch}',
                    style: TextStyle(
                      fontSize: 14,
                      color: ThemeColors.textSecondary,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 24),
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                      // 重置表单
                      _resetForm();
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: ThemeColors.primary,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20),
                      ),
                      padding: const EdgeInsets.symmetric(
                        horizontal: 24,
                        vertical: 10,
                      ),
                    ),
                    child: const Text('完成'),
                  ),
                ],
            ),
          ),
        );
      },
    );
  }

  // 重置表单
  void _resetForm() {
    setState(() {
      _selectedImage = null;
      _nameController.clear();
      _descriptionController.clear();
      _categoryController.clear();
      _artistController.clear();
      _selectedHeritageType = '传统工艺';
    });
  }

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    _categoryController.dispose();
    _artistController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('非遗数字藏品上链'),
        backgroundColor: ThemeColors.primary,
        elevation: 0,
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, size: 16, color: Colors.white),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 页面介绍
              Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: ThemeColors.primary.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: ThemeColors.primary.withOpacity(0.2),
                    width: 1,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '非遗数字藏品上链',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: ThemeColors.textPrimary,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      '将您的非遗资产数字化并上链，获得唯一的数字身份凭证，实现资产的溯源、认证和交易。',
                      style: TextStyle(
                        fontSize: 14,
                        color: ThemeColors.textSecondary,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 24),

              // 流程指示器
              Container(
                margin: const EdgeInsets.only(bottom: 24),
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _buildStepIndicator('资产上传', true),
                        _buildStepConnector(true),
                        _buildStepIndicator('认证评估', false),
                        _buildStepConnector(false),
                        _buildStepIndicator('价值锚定', false),
                        _buildStepConnector(false),
                        _buildStepIndicator('生成通证', false),
                        _buildStepConnector(false),
                        _buildStepIndicator('上链完成', false),
                      ],
                    ),
                  ],
                ),
              ),

              // 资产图片上传
              const Text(
                '上传资产图片',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: ThemeColors.textPrimary,
                ),
              ),
              const SizedBox(height: 8),
              GestureDetector(
                onTap: _pickImage,
                child: Container(
                  width: double.infinity,
                  height: 200,
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: ThemeColors.border,
                      width: 1,
                    ),
                    borderRadius: BorderRadius.circular(12),
                    color: ThemeColors.background,
                  ),
                  child: _selectedImage != null
                      ? Stack(
                          children: [
                            Image.file(
                              _selectedImage!,
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.cover,
                            ),
                            Positioned(
                              top: 8,
                              right: 8,
                              child: Container(
                                width: 32,
                                height: 32,
                                decoration: BoxDecoration(
                                  color: Colors.black.withOpacity(0.5),
                                  shape: BoxShape.circle,
                                ),
                                child: const Icon(
                                  Icons.close,
                                  color: Colors.white,
                                  size: 16,
                                ),
                              ),
                            ),
                          ],
                        )
                      : Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.cloud_upload_outlined,
                              size: 48,
                              color: ThemeColors.border,
                            ),
                            const SizedBox(height: 12),
                            Text(
                              '点击上传图片',
                              style: TextStyle(
                                fontSize: 14,
                                color: ThemeColors.textSecondary,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              '支持JPG、PNG格式，不超过5MB',
                              style: TextStyle(
                                fontSize: 12,
                                color: ThemeColors.textTertiary,
                              ),
                            ),
                          ],
                        ),
                ),
              ),
              const SizedBox(height: 24),

              // 资产信息表单
              const Text(
                '资产信息',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: ThemeColors.textPrimary,
                ),
              ),
              const SizedBox(height: 16),

              // 资产名称
              TextField(
                controller: _nameController,
                decoration: InputDecoration(
                  labelText: '资产名称',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              const SizedBox(height: 16),

              // 资产描述
              TextField(
                controller: _descriptionController,
                decoration: InputDecoration(
                  labelText: '资产描述',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                maxLines: 3,
              ),
              const SizedBox(height: 16),

              // 资产分类
              TextField(
                controller: _categoryController,
                decoration: InputDecoration(
                  labelText: '资产分类',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              const SizedBox(height: 16),

              // 艺术家/传承者
              TextField(
                controller: _artistController,
                decoration: InputDecoration(
                  labelText: '艺术家/传承者',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
              ),
              const SizedBox(height: 16),

              // 非遗类型选择
              DropdownButtonFormField<String>(
                value: _selectedHeritageType,
                onChanged: (String? newValue) {
                  if (newValue != null) {
                    setState(() {
                      _selectedHeritageType = newValue;
                    });
                  }
                },
                decoration: InputDecoration(
                  labelText: '非遗类型',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                items: _heritageTypes.map((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
              ),
              const SizedBox(height: 32),

              // 提交按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _isSubmitting ? null : _submitDigitization,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeColors.primary,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(24),
                    ),
                    padding: const EdgeInsets.symmetric(
                      vertical: 16,
                    ),
                    elevation: 4,
                  ),
                  child: _isSubmitting
                      ? const CircularProgressIndicator(
                          color: Colors.white,
                        )
                      : const Text(
                          '提交上链',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                ),
              ),
              const SizedBox(height: 24),

              // 上链说明
              Container(
                padding: const EdgeInsets.all(16.0),
                decoration: BoxDecoration(
                  color: ThemeColors.warning.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(
                    color: ThemeColors.warning.withOpacity(0.2),
                    width: 1,
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children:
                    [
                      Row(
                        children: [
                          Icon(
                            Icons.info_outline,
                            size: 16,
                            color: ThemeColors.warning,
                          ),
                          const SizedBox(width: 8),
                          const Text(
                            '上链说明',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w500,
                              color: ThemeColors.textPrimary,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(
                        '1. 上链后资产将获得唯一的数字身份凭证\n2. 上链过程大约需要3-5分钟\n3. 上链成功后可在个人中心查看资产\n4. 如有问题，请联系客服：400-123-4567',
                        style: TextStyle(
                          fontSize: 12,
                          color: ThemeColors.textSecondary,
                          height: 1.5,
                        ),
                      ),
                    ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}